package com.kzw.misc.freemarker.tags;

import java.io.IOException;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.kzw.oa.system.service.DictionaryService;

import freemarker.core.Environment;
import freemarker.template.Configuration;
import freemarker.template.DefaultObjectWrapperBuilder;
import freemarker.template.TemplateDirectiveBody;
import freemarker.template.TemplateDirectiveModel;
import freemarker.template.TemplateException;
import freemarker.template.TemplateModel;

/**
 * 下拉选择标签
 */
@Component
public class ComboDirective implements TemplateDirectiveModel {

	@Autowired
	private DictionaryService dictService;

	/**
	 * 传入model
	 * 传入where
	 */
	@SuppressWarnings("rawtypes")
	@Override
	public void execute(Environment env, Map map, TemplateModel[] loopVars, TemplateDirectiveBody body)
			throws TemplateException, IOException {
		
		if(map.containsKey("model") && map.get("model")!=null) {
			String model = map.get("model").toString();
			String hql = "from " + model;
			if(map.containsKey("where") && map.get("where")!=null) {
				String where = map.get("where").toString();
				if(!where.trim().equals("")) {
					hql += " where " + where; 
				}
			}
			List<Object> list = dictService.findByHQL(hql);

			DefaultObjectWrapperBuilder builder = new DefaultObjectWrapperBuilder(Configuration.VERSION_2_3_25);
			env.setVariable("items", builder.build().wrap(list));
			body.render(env.getOut());
		}

	}

}
